/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.util.core;

import com.blandware.atleap.common.util.DateUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.GenericValidator;
import org.apache.commons.validator.Validator;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.util.ValidatorUtils;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.Resources;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


/**
 * ValidationUtil Helper class for performing custom validations that
 * aren't already included in the core Struts Validator.
 * <p><a href="ValidationUtil.java.html"><i>View Source</i></a>
 * </p>
 *
 * @author Matt Raible <a href="mailto:matt@raibledesigns.com">&lt;matt@raibledesigns.com&gt;</a>
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.5 $ $Date: 2008/07/03 10:47:10 $
 */
public class ValidationUtil {

	protected transient final Log log = LogFactory.getLog(ValidationUtil.class);

	//~ Methods ================================================================

	/**
	 * Validates that two fields match (have the same value)
	 *
	 * @param bean      The bean to which a field belongs
	 * @param va        Validator action
	 * @param field     Form field to validate
	 * @param errors    Action messages that will accept validation error
	 * @param validator Validator
     * @param request   The request
	 * @return boolean Whether fields match
	 */
	public static boolean validateTwoFields(Object bean, ValidatorAction va,
	                                        Field field, ActionMessages errors,
                                            Validator validator,
                                            HttpServletRequest request) {
		String value =
		        ValidatorUtils.getValueAsString(bean, field.getProperty());
		String sProperty2 = field.getVarValue("secondProperty");
		String value2 = ValidatorUtils.getValueAsString(bean, sProperty2);

		if ( !GenericValidator.isBlankOrNull(value) ) {
			try {
				if ( !value.equals(value2) ) {
					errors.add(field.getKey(),
					        Resources.getActionMessage(validator, request, va, field));

					return false;
				}
			} catch ( Exception e ) {
				errors.add(field.getKey(),
				        Resources.getActionMessage(validator, request, va, field));

				return false;
			}
		}

		return true;
	}

	/**
	 * Validates date to match default date pattern for request locale without time symbols
	 *
	 * @param bean      The bean to which a field belongs
	 * @param va        Validator action
	 * @param field     Form field to validate
	 * @param errors    Action messages that will accept validation error
	 * @param validator Validator
	 * @param request   The request
	 * @return boolean Whether date matches pattern
	 */
	public static Date validateDate(Object bean, ValidatorAction va,
	                                Field field, ActionMessages errors,
                                    Validator validator,
                                    HttpServletRequest request) {

		Log log = LogFactory.getLog(ValidationUtil.class);

		if ( log.isDebugEnabled() ) {
			log.debug("validateDate called: field=" + field.getKey());
		}
		Date result = null;
		String value = ValidatorUtils.getValueAsString(bean, field.getProperty());

		if ( log.isDebugEnabled() ) {
			log.debug("Value: " + value);
		}

		Locale locale = (Locale) request.getSession().getAttribute(Globals.LOCALE_KEY);
		String datePattern = DateUtil.getDatePattern(locale);

		if ( log.isDebugEnabled() ) {
			log.debug("Date pattern: " + datePattern);
		}

		if ( !GenericValidator.isBlankOrNull(value) ) {
			try {
				SimpleDateFormat formatter = new SimpleDateFormat(datePattern, locale);
				formatter.setLenient(false);
				result = formatter.parse(value);
			} catch ( Exception e ) {
				if ( log.isErrorEnabled() ) {
					StringWriter sw = new StringWriter();
					e.printStackTrace(new PrintWriter(sw));
					log.error(sw.toString());
				}
			}
			if ( result == null ) {
				errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
			}
		}
		return result;
	}
}
